package supermarket;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;

//数据代码分离
//会员信息类,会员数量上限为100个
class MemberInfo {
    public static String[] memberName = new String[100]; 		// 会员姓名
    public static long[] memberPhone = new long[100];			// 会员手机号
    public static int[] memberAge = new int[100];				// 会员年龄
    public static double[] memberRemains = new double[100];		// 账户余额
    public static double[] memberScore = new double[100];		// 会员积分
    public static int memberCount = 0;							// 会员数量，同时也是会员信息记录数组下标，初始化0
}

//商品信息类
class GoodsInfo {
    public static String[] goodsNames = new String[1000];		// 商品名称
    public static String[] goodsIDs = new String[1000];			// 商品ID
    public static double[] goodsPrices = new double[1000];		// 商品价格
    public static int[] goodsStore = new int[1000];				// 商品库存
    public static int goodsCount = 0;							// 商品种数，初始化0
}

//购买记录类
class PurchaseRecord{
    // 使用二维数组记录购买信息：[订单索引][商品索引]
    public static int[][] purchasedGoodsIndex = new int[1000][]; // 最大1000个订单
    public static int[] orderUserIndex = new int[1000];        	 // 订单对应的用户索引
    public static double[] orderAmounts = new double[1000];      // 订单金额
    public static int orderCount = 0;                          	 // 当前订单数量
}

// 系统主体，超市管理系统类
public class SuperMarket {
    static {
        // 为测试方便，初始化3个会员数据，每人赠送1000积分
        MemberInfo.memberName[0] = "tom";
        MemberInfo.memberPhone[0] = 13538462947L;
        MemberInfo.memberAge[0] = 21;
        MemberInfo.memberRemains[0] = 100;
        MemberInfo.memberScore[0] = 1000;
        MemberInfo.memberName[1] = "jerry";
        MemberInfo.memberPhone[1] = 13728374058L;
        MemberInfo.memberAge[1] = 21;
        MemberInfo.memberRemains[1] = 500;
        MemberInfo.memberScore[1] = 1000;
        MemberInfo.memberName[2] = "kate";
        MemberInfo.memberPhone[2] = 13928364758L;
        MemberInfo.memberAge[2] = 21;
        MemberInfo.memberRemains[2] = 2300;
        MemberInfo.memberScore[2] = 1000;
        MemberInfo.memberCount = 3;
        // 初始化5个商品数据，每件商品库存50件
        GoodsInfo.goodsNames[0] = "book";
        GoodsInfo.goodsIDs[0] = "1001";
        GoodsInfo.goodsPrices[0] = 12.4;
        GoodsInfo.goodsStore[0] = 50;
        GoodsInfo.goodsNames[1] = "pencil";
        GoodsInfo.goodsIDs[1] = "1002";
        GoodsInfo.goodsPrices[1] = 1.62;
        GoodsInfo.goodsStore[1] = 50;
        GoodsInfo.goodsNames[2] = "ruler";
        GoodsInfo.goodsIDs[2] = "1003";
        GoodsInfo.goodsPrices[2] = 9.0;
        GoodsInfo.goodsStore[2] = 50;
        GoodsInfo.goodsNames[3] = "ereaser";
        GoodsInfo.goodsIDs[3] = "1004";
        GoodsInfo.goodsPrices[3] = 3.2;
        GoodsInfo.goodsStore[3] = 50;
        GoodsInfo.goodsNames[4] = "mouse";
        GoodsInfo.goodsIDs[4] = "1005";
        GoodsInfo.goodsPrices[4] = 56.0;
        GoodsInfo.goodsStore[4] = 50;
        GoodsInfo.goodsCount = 5;
    }

    /**
     * @author zhanghaoze
     * 系统主框架
     */
    private void start() {
        // TODO Auto-generated method stub
        while (true) {
            // 【1】显示菜单
            System.out.println("----------超市管理---------");
            System.out.println("|\t 1-商品管理\t|");
            System.out.println("|\t 2-会员管理\t|");
            System.out.println("|\t 3-结账\t\t|");
            System.out.println("|\t 4-销售统计\t|");
            System.out.println("|\t 5-积分兑换\t|");
            System.out.println("|\t 6-退出系统\t|");
            System.out.println("----------------------");
            System.out.println("请输入数字选择：");
            // 【2】键盘输入数字，选择菜单项
            Scanner in = new Scanner(System.in);
            int inputNo;// 输入的数字
            String tempInputNo = in.next();
            if (isInteger(tempInputNo)) {
                inputNo = Integer.parseInt(tempInputNo);
            }else {
                System.out.println("错误，用户输入不合法！");
                continue;
            }
            // 【3】根据数字选择不同的分支执行
            switch (inputNo) {
                case 1:
                    System.out.println("执行商品管理的功能");
                    goodsManage();
                    break;
                case 2:
                    System.out.println("执行会员管理的功能");
                    memberManage();
                    break;
                case 3:
                    System.out.println("执行结账的功能");
                    checkOut();
                    break;
                case 4:
                    System.out.println("执行销售统计的功能");
                    calculate();
                    break;
                case 5:
                    System.out.println("执行积分兑换的功能");
                    scoreExchange();
                    break;
                case 6:
                    System.out.println("执行退出功能");
                    System.exit(0);
                    break;
                default:
                    System.out.println("请输入数字1-6");

            }
        }
    }

    /**
     * @author zhanghaoze
     * 会员积分兑换功能
     * 目前仅支持100积分:1元的兑换功能，后续如果需要再增设更多功能
     */
    private void scoreExchange() {
        Scanner sc = new Scanner(System.in);

        // 输入并验证会员手机号
        System.out.println("----------积分兑换----------");
        System.out.println("请输入会员手机号：");
        String phoneInput = sc.next();
        if (!isLegalPhoneNumber(phoneInput)) {
            System.out.println("手机号格式错误！");
            return;
        }
        long phone = Long.parseLong(phoneInput);
        int memberIndex = selectMemberByPhone(phone);
        if (memberIndex == -1) {
            System.out.println("该会员不存在！");
            return;
        }

        // 显示当前积分和兑换比率
        double currentScore = MemberInfo.memberScore[memberIndex];
        System.out.printf("当前可用积分：%.2f%n", currentScore);
        System.out.println("当前兑换比率：每100积分兑换1元");

        // 输入兑换积分
        System.out.println("请输入要兑换的积分数量：");
        String scoreInput = sc.next();
        if (!isLegalPrice(scoreInput)) {
            System.out.println("输入不合法！请输入正数。");
            return;
        }
        double exchangeScore = Double.parseDouble(scoreInput);

        // 校验积分数量
        if (exchangeScore > currentScore) {
            System.out.println("积分不足，无法兑换！");
            return;
        }

        // 计算兑换金额并更新账户
        final double EXCHANGE_RATE = 100.0;
        double amount = exchangeScore / EXCHANGE_RATE;
        MemberInfo.memberRemains[memberIndex] += amount;
        MemberInfo.memberScore[memberIndex] -= exchangeScore;

        // 显示结果
        System.out.println("兑换成功！");
        System.out.printf("本次兑换获得：%.2f 元%n", amount);
        System.out.printf("账户余额：%.2f 元%n", MemberInfo.memberRemains[memberIndex]);
        System.out.printf("剩余积分：%.2f 分%n", MemberInfo.memberScore[memberIndex]);
    }

    /**
     * @author zhaoghaoze
     * 商品管理主框架
     */
    private void goodsManage() {
        // TODO Auto-generated method stub
        boolean flag = true;
        while (flag) {
            //【1】显示商品管理菜单
            System.out.println("------------商品管理------------");
            System.out.println("|\t 1-添加商品\t|");
            System.out.println("|\t 2-删除商品\t|");
            System.out.println("|\t 3-修改商品\t|");
            System.out.println("|\t 4-查找商品\t|");
            System.out.println("|\t 5-返回\t\t|");
            System.out.println("-------------------------------");
            System.out.println("请输入数字选择：");
            //【2】键盘输入选项
            Scanner in = new Scanner(System.in);
            int inputNo;// 输入的数字
            String tempInputNo = in.next();
            if (isInteger(tempInputNo)) {
                inputNo = Integer.parseInt(tempInputNo);
            }else {
                System.out.println("错误，用户输入不合法！");
                continue;
            }
            //【3】根据选项选择功能执行
            switch (inputNo) {
                case 1:
                    System.out.println("执行添加商品的功能");
                    addGoods();
                    break;
                case 2:
                    System.out.println("执行删除商品的功能");
                    deleteGoods();
                    break;
                case 3:
                    System.out.println("执行修改商品的功能");
                    updateGoods();
                    break;
                case 4:
                    System.out.println("执行查找商品的功能");
                    searchGoods();
                    break;
                case 5:
                    System.out.println("返回到主菜单");//返回主菜单
                    flag = false;//修改标志
                    break;//跳出switch
                default:
                    System.out.println("请输入数字1,2,3,4,5");
            }
        }
    }

    /**
     * @author gaoxiang
     * 商品查找功能
     */
    private void searchGoods() {
        // TODO Auto-generated method stub
        System.out.println("请选择查找方式：");
        boolean flag = true;
        Scanner in = new Scanner(System.in);
        while (flag) {
            System.out.println("按商品ID查找请按1，按商品名称查找请按2，按3返回上一页");
            int inputNo;// 输入的数字
            String tempInputNo = in.next();
            if (isInteger(tempInputNo)) {
                inputNo = Integer.parseInt(tempInputNo);
            }else {
                System.out.println("错误，用户输入不合法！");
                continue;
            }
            switch (inputNo) {
                case 1:
                    System.out.println("请输入商品ID：");
                    String ID = in.next();
                    int indexById = selectGoodsByID(ID);
                    if (indexById != -1) {
                        printGoodsInfo(indexById);
                    } else {
                        System.out.println("未找到该商品ID对应的商品，请重新输入。");
                    }
                    break;
                case 2:
                    System.out.println("请输入商品名称：");
                    String name = in.next();
                    int indexByName = selectGoodsByName(name);
                    if (indexByName != -1) {
                        printGoodsInfo(indexByName);
                    } else {
                        System.out.println("未找到该商品ID对应的商品，请重新输入");
                    }
                    break;
                case 3:
                    flag = false;	// 修改循环标志，跳出循环
                    break;
                default:
                    System.out.println("错误，请输入正确的数字！");
            }
        }
    }

    /**
     * @author gaoxiang
     * @param name
     * @return Index
     * 根据输入的商品名称返回商品在存储数组中的索引，找到返回索引，未找到返回-1
     */
    private int selectGoodsByName(String name) {
        for (int i = 0; i < GoodsInfo.goodsCount; i++) {
            if (GoodsInfo.goodsNames[i].equals(name)){
                return i;
            }
        }
        return -1;
    }

    /**
     * @author gaoxiang
     * @param ID
     * @return Index
     * 根据输入的商品ID返回商品在存储数组中的索引，找到返回索引，未找到返回-1
     */
    private int selectGoodsByID(String ID) {
        for (int i = 0; i < GoodsInfo.goodsCount; i++) {
            if (GoodsInfo.goodsIDs[i].equals(ID)) {
                return i;
            }
        }
        return -1;
    }

    /**
     * @author xuefulin
     * 商品信息修改功能
     */
    private void updateGoods() {
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入要更新的商品ID：");
        String goodsID = sc.next();  // 输入要更新的商品ID
        sc.nextLine(); // 清理换行符

        int index = selectGoodsByID(goodsID);  // 查找商品索引
        if (index == -1) {
            System.out.println("未找到该商品，请检查商品ID！退回商品管理页面");
            return;  // 商品未找到，返回
        }

        // 如果找到了商品，显示当前商品信息
        System.out.println("当前商品信息如下：");
        System.out.println("商品名称: " + GoodsInfo.goodsNames[index]);
        System.out.println("商品价格: " + GoodsInfo.goodsPrices[index]);

        // 输入新的商品名称和价格
        System.out.println("请输入新的商品名称（若不修改请按回车）：");
        String newName = sc.nextLine();
        if (!newName.isEmpty()) {
            GoodsInfo.goodsNames[index] = newName;  // 更新商品名称
        }

        System.out.println("请输入新的商品价格（若不修改请按回车）：");
        String newPriceInput = sc.nextLine();
        if (!newPriceInput.isEmpty()) {
            if (isLegalPrice(newPriceInput)) {
                double newPrice = Double.parseDouble(newPriceInput);
                GoodsInfo.goodsPrices[index] = newPrice;  // 更新商品价格
            } else {
                System.out.println("错误，商品价格不合法！未做修改！");
            }
        }

        System.out.println("商品信息更新成功！");
    }

    /**
     * @author fanyong
     * 商品删除功能
     */
    private void deleteGoods() {
        // 【1】提示用户选择删除方式
        Scanner sc = new Scanner(System.in);
        System.out.println("选择删除方式：");
        System.out.println("1 - 按商品ID删除");
        System.out.println("2 - 按商品名称删除");
        int choice;
        String tempchoice = sc.next();
        if (isInteger(tempchoice)) {
            choice = Integer.parseInt(tempchoice);
        } else {
            System.out.println("错误，用户输入非法！退出商品删除页面");
            return;
        }

        if (choice == 1) {
            // 按商品ID删除
            System.out.println("请输入要删除的商品ID：");
            String goodsID = sc.next();

            // 查找商品ID对应的商品
            int index = selectGoodsByID(goodsID);

            if (index == -1) {
                // 商品未找到
                System.out.println("未找到商品ID为 " + goodsID + " 的商品。");
            } else {
                deleteGoodsByIndex(index);
                System.out.println("商品ID为 " + goodsID + " 的商品已成功删除。");
            }
        } else if (choice == 2) {
            System.out.println("请输入要删除的商品名称：");
            String goodsName = sc.next();

            // 查找所有匹配的商品
            List<Integer> indexes = new ArrayList<>();
            for (int i = 0; i < GoodsInfo.goodsCount; i++) {
                if (GoodsInfo.goodsNames[i].equals(goodsName)) {
                    indexes.add(i);
                }
            }

            if (indexes.isEmpty()) {
                System.out.println("未找到商品");
            } else if (indexes.size() == 1) {
                // 唯一匹配项直接删除
                deleteGoodsByIndex(indexes.get(0));
                System.out.println("商品" + goodsName + "已成功删除。");
            } else {
                // 显示所有匹配商品
                System.out.println("找到多个同名商品，请按ID删除：");
                for (int idx : indexes) {
                    System.out.printf("ID: %s, 名称: %s%n",
                            GoodsInfo.goodsIDs[idx], GoodsInfo.goodsNames[idx]);
                }
            }
        } else {
            System.out.println("无效的选择，请输入1或2。");
        }
    }

    /**
     * @author fanyong
     * @param index
     * 根据输入的商品索引删除保存的商品信息
     */
    private void deleteGoodsByIndex(int index) {
        // 【3】删除商品逻辑
        // 将商品信息清空
        GoodsInfo.goodsNames[index] = null;
        GoodsInfo.goodsIDs[index] = null;
        GoodsInfo.goodsPrices[index] = 0.0;

        // 【4】元素移位，保证数组连续性
        for (int i = index; i < GoodsInfo.goodsCount - 1; i++) {
            GoodsInfo.goodsNames[i] = GoodsInfo.goodsNames[i + 1];
            GoodsInfo.goodsIDs[i] = GoodsInfo.goodsIDs[i + 1];
            GoodsInfo.goodsPrices[i] = GoodsInfo.goodsPrices[i + 1];
        }
        // 清空最后一个元素以避免数据残留
        GoodsInfo.goodsNames[GoodsInfo.goodsCount - 1] = null;
        GoodsInfo.goodsIDs[GoodsInfo.goodsCount - 1] = null;
        GoodsInfo.goodsPrices[GoodsInfo.goodsCount - 1] = 0.0;

        // 【5】更新商品数量
        GoodsInfo.goodsCount--;

    }

    /**
     * @author gongyujie
     * 添加商品
     */
    private void addGoods() {
        // 检查商品数量是否已达到上限
        if (GoodsInfo.goodsCount >= GoodsInfo.goodsNames.length) {
            System.out.println("商品数量已达上限，无法继续添加！");
            return;
        }

        Scanner sc = new Scanner(System.in);

        // 输入商品名称
        System.out.println("请输入商品名称：");
        String goodsName = sc.next();

        // 输入商品ID
        System.out.println("请输入商品ID：");
        String goodsID = sc.next();

        // 检查商品ID是否重复
        for (int i = 0; i < GoodsInfo.goodsCount; i++) {
            if (GoodsInfo.goodsIDs[i] != null && GoodsInfo.goodsIDs[i].equals(goodsID)) {
                System.out.println(goodsID+"号商品已存在！退出商品添加页面");
                return;
            }
        }

        // 输入商品价格
        System.out.println("请输入商品价格：");
        double goodsPrice;
        String tempGoodsPrice = sc.next();
        if (isLegalPrice(tempGoodsPrice)) {
            goodsPrice = Double.parseDouble(tempGoodsPrice);
        } else {
            System.out.println("错误，商品价格输入不合法！");
            return;
        }

        // 添加商品信息
        GoodsInfo.goodsNames[GoodsInfo.goodsCount] = goodsName;
        GoodsInfo.goodsIDs[GoodsInfo.goodsCount] = goodsID;
        GoodsInfo.goodsPrices[GoodsInfo.goodsCount] = goodsPrice;
        GoodsInfo.goodsStore[GoodsInfo.goodsCount] = 50;	// 默认50库存

        // 更新商品数量
        GoodsInfo.goodsCount++;

        System.out.println("商品添加成功！");
    }

    /**
     * @author zhanghaoze
     * 购买记录统计功能框架
     */
    private void calculate() {
        Scanner sc = new Scanner(System.in);
        boolean flag = true;
        while (flag) {
            System.out.println("------------销售统计------------");
            System.out.println("|\t 1-按用户统计总消费\t|");
            System.out.println("|\t 2-显示用户购买记录\t|");
            System.out.println("|\t 3-返回\t\t\t|");
            System.out.println("-------------------------------");
            System.out.println("请输入数字选择：");
            int choice;
            String tempChoice = sc.next();
            if (isInteger(tempChoice)) {
                choice = Integer.parseInt(tempChoice);
            } else {
                System.out.println("输入错误，请重新输入！");
                continue;
            }
            switch (choice) {
                case 1:
                    calculateUserTotal();
                    break;
                case 2:
                    displayUserPurchases();
                    break;
                case 3:
                    flag = false;
                    break;
                default:
                    System.out.println("请输入1-3之间的数字！");
            }
        }
    }

    /**
     * @author zhanghaoze
     * 逐行输出用户的消费记录功能
     */
    private void displayUserPurchases() {
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入会员手机号：");
        String phoneInput = sc.next();
        if (!isLegalPhoneNumber(phoneInput)) {
            System.out.println("手机号格式错误！");
            return;
        }
        long phone = Long.parseLong(phoneInput);
        int userIndex = selectMemberByPhone(phone);
        if (userIndex == -1) {
            System.out.println("该用户不存在！");
            return;
        }
        System.out.println("用户 " + MemberInfo.memberName[userIndex] + " 的购买记录：");
        boolean hasRecord = false;
        for (int i = 0; i < PurchaseRecord.orderCount; i++) {
            if (PurchaseRecord.orderUserIndex[i] == userIndex) {
                hasRecord = true;
                System.out.println("订单 " + (i + 1) + "：");
                System.out.println("金额：" + PurchaseRecord.orderAmounts[i]);
                System.out.println("商品列表：");
                int[] goodsIndexes = PurchaseRecord.purchasedGoodsIndex[i];
                for (int j = 0; j < goodsIndexes.length; j++) {
                    int goodsIndex = goodsIndexes[j];
                    System.out.printf("- %s (ID: %s) 单价: %.2f%n",
                            GoodsInfo.goodsNames[goodsIndex],
                            GoodsInfo.goodsIDs[goodsIndex],
                            GoodsInfo.goodsPrices[goodsIndex]);
                }
                System.out.println("-------------------");
            }
        }
        if (!hasRecord) {
            System.out.println("该用户暂无购买记录。");
        }
    }

    /**
     * @author zhanghaoze
     * 统计用户购买的总消费金额功能
     */
    private void calculateUserTotal() {
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入会员手机号：");
        String phoneInput = sc.next();
        if (!isLegalPhoneNumber(phoneInput)) {
            System.out.println("手机号格式错误！");
            return;
        }
        long phone = Long.parseLong(phoneInput);
        int userIndex = selectMemberByPhone(phone);
        if (userIndex == -1) {
            System.out.println("该用户不存在！");
            return;
        }
        double total = 0;
        for (int i = 0; i < PurchaseRecord.orderCount; i++) {
            if (PurchaseRecord.orderUserIndex[i] == userIndex) {
                total += PurchaseRecord.orderAmounts[i];
            }
        }
        System.out.printf("用户 %s 的总消费金额为：%.2f%n", MemberInfo.memberName[userIndex], total);
    }

    /**
     * @author zhanghaoze
     * 结账功能
     */
    private void checkOut() {
        // TODO Auto-generated method stub
        // 定义购物车，4个数组，存放结账商品的name、id、price和商品在商品Info中的索引，用于打印购物小票
        String[] shoppingCartNames = new String[50];
        String[] shoppingCartIDs = new String[50];
        double[] shoppingCartPrices = new double[50];
        int[] shoppingCartIndexes = new int[50];
        int shoppingCartCount = 0;// 购物车商品数量，同时作为购物车数组的下标
        double total = 0;//总价
        // 【1】扫描商品,输入商品条形码，即id
        System.out.println("\n----------------扫描商品------------------");
        Scanner sc = new Scanner(System.in);
        for (int i = 0; i < 50; i++) {
            System.out.println("请扫描第" + (i + 1) + "件商品id：（若要停止扫描请输入n/N）");
            String input = sc.next();
            if (input.equals("n") || input.equals("N")) {
                System.out.println("扫描停止");
                break;
            }
            // 【2】在商品id数组查找查找商品信息。找到返回下标值，没找到返回-1
            int goodsIndex = selectGoodsByID(input);
            if (goodsIndex == -1) {
                // 没找到商品信息
                System.out.println("没找到商品,重新扫描");
                i--;
                continue;
            } else if(GoodsInfo.goodsStore[goodsIndex] < 1) {
                // 商品库存不足
                System.out.println("抱歉，商品：" + GoodsInfo.goodsNames[goodsIndex] + "已售完");
                i--;
                continue;
            } else {
                // 显示扫描商品部的信息，并将信息存储到对应的3个数组
                shoppingCartNames[shoppingCartCount] = GoodsInfo.goodsNames[goodsIndex];
                shoppingCartIDs[shoppingCartCount] = GoodsInfo.goodsIDs[goodsIndex];
                shoppingCartPrices[shoppingCartCount] = GoodsInfo.goodsPrices[goodsIndex];
                shoppingCartIndexes[shoppingCartCount] = goodsIndex;
                total += shoppingCartPrices[shoppingCartCount];
                System.out.println("商品名称：" + shoppingCartNames[shoppingCartCount] + " \t编号："
                        + shoppingCartIDs[shoppingCartCount] + " \t价格：" + shoppingCartPrices[shoppingCartCount]);
                shoppingCartCount++;// 更新购物车数组下标
            }
        }

        // 特殊情况判断
        if (shoppingCartCount < 1) {
            System.out.println("未扫描到任何商品，取消结账");
            return;
        }

        // 【3】显示购物清单,将存放结账商品的购物车信息输出
        System.out.println("--------------商品清单--------------");
        System.out.println("商品名称\t\tt商品编号：\t\t商品价格：");
        for (int i = 0; i < shoppingCartCount; i++) {
            System.out.println(shoppingCartNames[i] + "\t\t编号："+ shoppingCartIDs[i] + " \t\t价格：" + shoppingCartPrices[i]);
        }
        System.out.println("----------------------------------");
        System.out.printf("应付金额：%.2f%n", total);
        // 【4】会员卡付款,找到会员信息，将会员余额减去付款金额total
        System.out.println("请登录会员以支付：");
        while (true) {
            System.out.println("请输入会员手机号（取消支付请按b/B）");
            long phone;
            String tempPhone = sc.next();
            if (tempPhone.equals("b") || tempPhone.equals("B")) {
                System.out.println("用户取消支付");
                break;
            }
            // 判断手机号输入合法性
            if (isLegalPhoneNumber(tempPhone)) {
                phone = Long.parseLong(tempPhone);
                int memberIndex = selectMemberByPhone(phone);
                if (memberIndex != -1) {
                    if (memberPay(memberIndex, total) != -1) {

                        //防溢出判断
                        if (PurchaseRecord.orderCount >= PurchaseRecord.purchasedGoodsIndex.length) {
                            System.out.println("系统订单已达上限，无法完成支付");
                            break;
                        }

                        // 支付成功，更新商品库存，并赠与会员积分
                        for (int i = 0; i < shoppingCartCount; i++) {
                            int goodsIndex = shoppingCartIndexes[i];
                            GoodsInfo.goodsStore[goodsIndex]--;
                            MemberInfo.memberScore[memberIndex] += GoodsInfo.goodsPrices[goodsIndex];
                        }
                        // 将本次购物信息记录在统计数组中
                        int currentOrder = PurchaseRecord.orderCount;
                        PurchaseRecord.purchasedGoodsIndex[currentOrder] = Arrays.copyOf(shoppingCartIndexes, shoppingCartCount);
                        PurchaseRecord.orderUserIndex[currentOrder] = memberIndex;
                        PurchaseRecord.orderAmounts[currentOrder] = total;
                        PurchaseRecord.orderCount++;

                        System.out.printf("支付成功！用户"+MemberInfo.memberName[memberIndex]+"余额为%.2f%n", MemberInfo.memberRemains[memberIndex]);
                        break;

                    }else {
                        System.out.println("支付失败！用户"+MemberInfo.memberName[memberIndex]+"余额不足！请重新登录或先取消支付后充值！");
                    }
                }else {
                    System.out.println("错误，未找到该用户，请重新输入或先注册再购物！");
                    continue;
                }
            }else {
                System.out.println("错误，用户输入手机号不合法！请重新输入！");
                continue;
            }
        }
    }

    /**
     * @author zhanghaoze
     * 会员支付
     * @param index
     * @param total
     * @return 0表示支付成功，-1表示支付失败
     */
    private int memberPay(int index, double total) {
        // TODO Auto-generated method stub
        //先判断用户余额是否大于购物车总花费
        if (MemberInfo.memberRemains[index] >= total) {
            MemberInfo.memberRemains[index] -= total;
            return 0;			//扣除用户余额后返回正常结束代码0
        }else {
            return -1;			//若用户余额不足，返回错误代码-1
        }
    }

    /**
     * @author zhanghaoze
     * 会员管理
     */
    private void memberManage() {
        boolean flag = true;
        while (flag) {
            //【1】显示会员管理菜单
            System.out.println("------------会员管理------------");
            System.out.println("|\t 1-注册会员\t\t|");
            System.out.println("|\t 2-充值\t\t\t|");
            System.out.println("|\t 3-显示所有会员信息\t|");
            System.out.println("|\t 4-返回\t\t\t|");
            System.out.println("-------------------------------");
            System.out.println("请输入数字选择：");
            //【2】键盘输入选项
            Scanner in = new Scanner(System.in);
            int inputNo;// 输入的数字
            String tempInputNo = in.next();
            if (isInteger(tempInputNo)) {
                inputNo = Integer.parseInt(tempInputNo);
            }else {
                System.out.println("错误，用户输入不合法！");
                continue;
            }
            //【3】根据选项选择功能执行
            switch (inputNo) {
                case 1:
                    System.out.println("执行注册会员的功能");
                    registerMember();
                    break;
                case 2:
                    System.out.println("执行充值的功能");
                    rechargeMember();
                    break;
                case 3:
                    System.out.println("显示所有会员信息的功能");
                    selectAllMember();
                    break;
                case 4:
                    System.out.println("返回到主菜单");//返回主菜单，即跳出会员管理菜单的循环
                    flag = false;//修改标志
                    break;//跳出switch
                default:
                    System.out.println("请输入数字1,2,3,4");
            }
        }
    }

    /**
     * @author zhanghaoze
     * 输出所有会员的信息
     */
    private void selectAllMember() {
        // TODO Auto-generated method stub
        //显示所有会员信息
        System.out.println("-----显示所有会员信息-----");
        for (int i = 0; i < MemberInfo.memberCount; i++) {
            //显示一个会员信息-----方法
            selectMemberByIndex(i);
        }
    }

    /**
     * @author zhanghaoze
     * @param index
     * @return memberInfo
     * 根据输入的存储数组索引返回会员的信息
     */
    private void selectMemberByIndex(int index) {
        // TODO Auto-generated method stub
        System.out.println("会员姓名："+MemberInfo.memberName[index]);
        System.out.println("手机号："+MemberInfo.memberPhone[index]);
        System.out.println("年龄："+MemberInfo.memberAge[index]);
        System.out.println("账户余额："+MemberInfo.memberRemains[index]);
        System.out.println("会员积分："+MemberInfo.memberScore[index]);
    }

    /**
     * @author zhanghaoze
     * 会员充值功能框架
     */
    private void rechargeMember() {
        // TODO Auto-generated method stub
        //【1】增加会员余额的字段
        //【2】输入会员的手机号（唯一不重复）---给这个会员充值
        Scanner sc = new Scanner(System.in);//手机号
        System.out.println("请输入会员的手机号：");
        long memberPhone;
        String tempMemberPhone = sc.next();
        if (isLegalPhoneNumber(tempMemberPhone)) {
            memberPhone = Long.parseLong(tempMemberPhone);
        }else {
            System.out.println("错误，输入不合法！");
            return;
        }
        //【3】从会员手机数组中找到这个会员，找到---记录位置|没找到---提示 ，先注册再充值
        int index=selectMemberByPhone(memberPhone);
        if (index == -1) {
            //没找到
            System.out.println(memberPhone+"不存在，请先注册再充值");
            return;
        }
        //【4】找到---修改会员余额
        System.out.println("找到会员信息");
        int flag = increaseMemberRemain(index);
        if (flag == 0) {
            //【5】显示充值后的会员余额值
            System.out.println(memberPhone+"充值成功");
            selectMemberByIndex(index);
        }
    }

    /**
     * @author zhanghaoze
     * @param index
     * @return flag
     * 根据输入的索引，找到会员信息，修改会员余额，然后返回状态码。（0表示充值成功，-1表示充值失败）
     */
    private int increaseMemberRemain(int index) {
        // TODO Auto-generated method stub
        Scanner sc = new Scanner(System.in);
        System.out.print("请输入您要充值的金额（元）：");
        int recharge = 0;// 充值金额
        try {
            recharge = sc.nextInt();
        }catch (Exception e) {
            System.out.println("错误，请输入正确的数字！");
            return -1;
        }

        int increase = 0;// 赠送金额
        if (recharge > 0 && recharge < 100) {
            increase = 0;
        } else if (recharge >= 100 && recharge < 200) {
            increase = 10;

        } else if (recharge >= 200 && recharge < 500) {
            increase = 30;

        } else if (recharge >= 500 && recharge < 1000) {
            increase = 80;

        } else if (recharge >= 1000) {
            increase = 200;
        } else {
            increase = 0;
            System.out.println("充值失败!金额错误!");
            return -1;
        }
        recharge = recharge + increase;
        // 修改余额
        MemberInfo.memberRemains[index] += recharge;
        return 0;
    }

    /**
     * @author zhanghaoze
     * @param memberPhone
     * @return Index
     * 根据输入的会员手机号，返回会员在存储数组中的索引，找到返回索引，未找到返回-1
     */
    private int selectMemberByPhone(long memberPhone) {
        // TODO Auto-generated method stub
        for (int i = 0; i < MemberInfo.memberCount; i++) {
            if (MemberInfo.memberPhone[i] == memberPhone) {
                //找到
                return i;//返回下标值
            }
        }
        return -1;//没找到
    }

    /**
     * @author zhanghaoze
     *注册会员
     */
    private void registerMember() {
        // 会员数量上限检查，防止溢出
        if (MemberInfo.memberCount >= MemberInfo.memberName.length) {
            System.out.println("会员数量已达上限，无法注册！");
            return;
        }

        //【1】键盘输入会员的信息
        System.out.println("----------欢迎进入会员注册------------");
        System.out.println("请输入会员的姓名：");
        //输入，首先创建一个Scanner类型的对象
        Scanner sc = new Scanner(System.in);
        //输入，接下来，定义一个变量存储输入的数据
        String memberName;
        //键盘输入数据存放到变量
        memberName=sc.next();
        System.out.println("请输入会员的手机号：");
        long memberPhone;//手机号
        String tempMemberPhone=sc.next();

        //合法性检查
        if (isLegalPhoneNumber(tempMemberPhone)) {
            memberPhone = Long.parseLong(tempMemberPhone);
        }else {
            System.out.println("错误，输入不合法！");
            return;
        }

        //唯一性检查
        if (selectMemberByPhone(memberPhone) != -1) {
            System.out.println("该用户已注册！");
            return;
        }

        System.out.println("请输入会员的年龄：");
        int memberAge;
        String tempMemberAge = sc.next();

        //合法性检查
        if (isLegalAge(tempMemberAge)) {
            memberAge = Integer.parseInt(tempMemberAge);
        }else {
            System.out.println("错误，输入不合法！");
            return;
        }

        //【2】保存会员信息
        MemberInfo.memberName[MemberInfo.memberCount]=memberName;
        MemberInfo.memberPhone[MemberInfo.memberCount]=memberPhone;
        MemberInfo.memberAge[MemberInfo.memberCount]=memberAge;
        //【3】显示会员信息
        System.out.println("----注册成功--------");
        selectMemberByIndex(MemberInfo.memberCount);
        MemberInfo.memberCount++;//会员人数加1
    }

    /**
     * @author zhanghaoze
     * @param index
     * @return goodsInfo
     * 根据输入的商品索引，输出商品的信息
     */
    private void printGoodsInfo(int index) {
        System.out.println("----- 商品信息 -----");
        System.out.println("商品名称: " + GoodsInfo.goodsNames[index]);
        System.out.println("商品ID: " + GoodsInfo.goodsIDs[index]);
        System.out.println("商品价格: " + GoodsInfo.goodsPrices[index]);
        System.out.println("商品库存: " + GoodsInfo.goodsStore[index]);
        System.out.println("---------------------");
    }

    /**
     * @author zhanghaoze
     * @param input
     * @return boolean
     * 检查用户的输入的年龄是否合法
     */
    public static boolean isLegalAge(String input) {
        try {
            int tempAge = Integer.parseInt(input);
            return 0 <= tempAge && tempAge <= 120;
        } catch (NumberFormatException e) {
            return false;
        }
    }

    /**
     * @author zhanghaoze
     * @param input
     * @return boolean
     * 检查用户输入的手机号是否合法
     */
    public static boolean isLegalPhoneNumber(String input) {
        try {
            long tempPhone = Long.parseLong(input);
            return 10_000_000_000L <= tempPhone && tempPhone <= 99_999_999_999L;
        } catch (NumberFormatException e) {
            return false;
        }
    }

    /**
     * @author zhanghaoze
     * @param input
     * @return boolean
     * 检查用户的输入是否是整形
     */
    public static boolean isInteger(String input) {
        try {
            Integer.parseInt(input);
            return true;
        } catch (NumberFormatException e) {
            return false;
        }
    }

    /**
     * @author zhanghaoze
     * @param tempGoodsPrice
     * @return boolean
     */
    public static boolean isLegalPrice(String tempGoodsPrice) {
        try {
            double price = Double.parseDouble(tempGoodsPrice);
            return price > 0;
        } catch (NumberFormatException e) {
            return false;
        }
    }

    /**
     * @author zhanghaoze
     * 主程序入口
     */
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        String name;	//用户名
        int password;	//密码

        while(true) {
            System.out.println("请输入管理员用户名：");
            name = in.next();			//键盘输入字符串
            System.out.println("请输入管理员密码：");
            String temppassword = in.next();	//键盘输入整型数
            if (isInteger(temppassword)) {
                password = Integer.parseInt(temppassword);
            } else {
                System.out.println("错误，密码格式非法！");
                continue;
            }
            //2-匹配，用户名固定admin。密码固定123
            //字符串相等的比较方法，equals方法
            if(name.equals("admin") && password == 123) {
                //匹配成功，进入系统
                new SuperMarket().start();
            }
            //不匹配，重新输入=继续下一次循环
            System.out.println("不匹配，重新输入");
        }
    }
}
